// pages/realTestDetail/realTestDetail.js
const app = getApp()
import api from '../../utils/api.js';
let timer
let leftTime
let subject_num
let arr = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    questions: [],
    currentIndex: 0,
    // isCollect: false,
    isShowtab: false,
    isShowSubmit: false,
    isShowQuitTest: false,
    isShowContinue: false,

    finishedQuestion: []
  },

  // 选择答案
  chooseAnswer(e) {
    if (this.data.questions[this.data.currentIndex].true_answer.length > 1) {
      if (arr.indexOf(e.currentTarget.dataset.index) == -1) {
        arr.push(e.currentTarget.dataset.index)

      } else {
        let index = arr.indexOf(e.currentTarget.dataset.index)
        arr.splice(index, 1)
      }
      arr.sort(function(a, b) {
        return a - b
      })
      console.log(arr)
      this.data.questions[this.data.currentIndex].yourIndex = arr

      let answerArr = arr.map(item => {
        return this.data.questions[this.data.currentIndex].options[item].slice(0, 1)
      })
      console.log(answerArr)
      this.data.questions[this.data.currentIndex].answer = answerArr.join('|')
      // let answerArr = arr.map(item=>{
      //   return this.data.questions[this.data.currentIndex].options[item].slice(0,1)
      // })
      // console.log(answerArr)
      // this.data.questions[this.data.currentIndex].answer = answerArr.join('|')

      this.setData({
        questions: this.data.questions
      })
    } else {
      // 显示蓝色
      this.data.questions[this.data.currentIndex].yourIndex = [e.currentTarget.dataset.index]

      // this.setData({
      //   questions: this.data.questions
      // })

      this.data.questions[this.data.currentIndex].answer = this.data.questions[this.data.currentIndex].options[e.currentTarget.dataset.index].slice(0, 1)

      // let yourAnswer = this.data.questions[this.data.currentIndex].options[e.currentTarget.dataset.index].slice(0, 1)
      // this.data.questions[this.data.currentIndex].yourAnswer = yourAnswer
      // console.log(this.data.questions[this.data.currentIndex])

      // api.POST('applet/customerSubject/create', {
      //   subject_id: this.data.questions[this.data.currentIndex].subject_id,
      //   answer: yourAnswer,
      //   type: 2
      // }, res => {
      //   console.log(res)
      // })

      // this.data.questions[this.data.currentIndex].isChoice = false

    }
    if (this.data.finishedQuestion.indexOf(this.data.currentIndex) == -1) {
      this.data.finishedQuestion.push(this.data.currentIndex)
    }

    this.setData({
      questions: this.data.questions,
      finishedQuestion: this.data.finishedQuestion
    })

  },

  // 滑动
  start(e) {
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY
    })
  },

  end(e) {
    let endX = e.changedTouches[0].clientX;
    let endY = e.changedTouches[0].clientY;

    if (endX - this.data.startX > 50 && Math.abs(endY - this.data.startY) < 50) {
      // 右滑
      if (this.data.currentIndex > 0) {
        arr = []
        this.data.currentIndex--;
        this.setData({
          currentIndex: this.data.currentIndex
        })
      } else {
        return
      }
    } else if (this.data.startX - endX > 50 && Math.abs(endY - this.data.startY) < 50) {
      // 左滑
      arr = []
      if (this.data.currentIndex < this.data.questions.length - 1) {
        this.data.currentIndex++;
        this.setData({
          currentIndex: this.data.currentIndex
        })
      } else {
        wx.showToast({
          title: '已经是最后一题了',
          icon: "loading"
        })
      }
    }
  },

  // 点击按钮进入上一题
  preQues() {
    if (this.data.currentIndex > 0) {
      this.data.currentIndex--;
      this.setData({
        currentIndex: this.data.currentIndex
      })
    } else {
      return
    }
  },

  // 点击按钮进入下一题
  nextQues() {
    if (this.data.currentIndex < this.data.questions.length - 1) {
      this.data.currentIndex++;
      this.setData({
        currentIndex: this.data.currentIndex
      })
    } else {
      wx.showToast({
        title: '已经是最后一题了',
        icon: "none"
      })
    }
  },
  // 收藏状态
  collect() {
    this.data.questions[this.data.currentIndex].status = !this.data.questions[this.data.currentIndex].status
    this.setData({
      questions: this.data.questions
    })
    api.POST('applet/SubjectFavorite/create', {
      subject_id: this.data.questions[this.data.currentIndex].subject_id
    }, res => {
      console.log(res)
    })
  },
  // 答题卡
  showTab() {
    this.setData({
      isShowtab: true
    })

  },
  closeTab() {
    this.setData({
      isShowtab: false
    })
  },
  changeCurrentIndex(e) {
    this.setData({
      currentIndex: e.currentTarget.dataset.index
    })
  },
  // 交卷 status 2 发送答案
  submitPaper() {
    let n = 0;
    for (let i = 0; i < this.data.questions.length; i++) {
      if (this.data.questions[i].answer) {
        n++
      }
    }
    this.setData({
      subjectNum: n
    })
    // 判断是不是最后一题
    let yourAnswers = []
    if (this.data.currentIndex == this.data.totalNum - 1) {
      for (let i = 0; i < this.data.questions.length; i++) {
        yourAnswers[i] = {
          "subject_id": this.data.questions[i].subject_id,
          "answer": this.data.questions[i].answer ? this.data.questions[i].answer : ""
        }
      }
      api.POST('applet/customerSubject/paperCreate', {
        paper_id: this.data.paper_id,
        status: 2,
        answer: yourAnswers
      }, res => {
        console.log(res)
        wx.redirectTo({
          url: '/pages/realTestGrade/realTestGrade?errorNum=' + res.data.errorNum + '&rightNum=' + res.data.rightNum + '&grade=' + res.data.grade + '&paper_id=' + this.data.paper_id
        })

      })
    } else {
      this.setData({
        isShowSubmit: true
      })

    }

  },
  goToGrade() {
    let yourAnswers = []
    for (let i = 0; i < this.data.questions.length; i++) {
      yourAnswers[i] = {
        "subject_id": this.data.questions[i].subject_id,
        "answer": this.data.questions[i].answer ? this.data.questions[i].answer : ""
      }
    }
    console.log(yourAnswers)
    api.POST('applet/customerSubject/paperCreate', {
      paper_id: this.data.paper_id,
      status: 2,
      answer: yourAnswers
    }, res => {
      console.log(res)
      wx.redirectTo({
        url: '/pages/realTestGrade/realTestGrade?errorNum=' + res.data.errorNum + '&rightNum=' + res.data.rightNum + '&grade=' + res.data.grade + '&paper_id=' + this.data.paper_id
      })
    })

  },
  closeSubmit() {
    this.setData({
      isShowSubmit: false
    })
  },

  // 左上角退出
  showQuitTest() {
    let n = 0;
    for (let i = 0; i < this.data.questions.length; i++) {
      if (this.data.questions[i].answer) {
        n++
      }
    }
    this.setData({
      subjectNum: n,
      isShowQuitTest: true
    })
  },
  closeQuitTest() {
    this.setData({
      isShowQuitTest: false
    })
  },
  // status 1
  confirmQuitTest() {
    console.log(5215)
    const that = this
    this.setData({
      isShowQuitTest: false
    })
    wx.navigateBack({
      delta: 1
    })
    let yourAnswers = []

    for (let i = 0; i < this.data.questions.length; i++) {
      yourAnswers[i] = {
        "subject_id": this.data.questions[i].subject_id,
        "answer": this.data.questions[i].answer ? this.data.questions[i].answer : ""
      }
    }

    console.log(yourAnswers)
    api.POST('applet/customerSubject/paperCreate', {
      paper_id: this.data.paper_id,
      status: 1,
      answer: yourAnswers,
      last_timing: that.data.time
    }, res => {
      console.log(res)
      subject_num = res.data.subject_num
    })
  },
  // 重新考试
  redo() {
    api.POST('applet/subject/examFinds', {
      paper_id: this.data.paper_id,
      status: 3,
      type: this.data.type
    }, res => {
      console.log(res)
      res.data.map((item, index) => {
        item.name = index + 1 + item.name
      })
      this.setData({
        questions: res.data
      })
      for (let i = 0; i < this.data.questions.length; i++) {
        this.data.questions[i].yourIndex = null
        // this.data.questions[i].isChoice = true
        // this.data.questions[i].status = false
      }
    })
    this.setData({
      questions: this.data.questions,
      isShowContinue: false,
      currentIndex: 0,
      time: 0
    })
    clearTimeout(timer)
    this.countdown()
  },
  closeContinue() {
    this.setData({
      isShowContinue: false
    })
  },


  // 获取试题
  getPaperQuestion() {
    api.POST('applet/subject/examFinds', {
        paper_id: this.data.paper_id,
        status: this.data.status,
        type: this.data.type
      },
      res => {
        console.log(res)
        if (res.data.data) {
          res.data.data.map((item, index) => {
            item.name = index + 1 + item.name
            item.yourIndex = null
          })
          this.setData({
            questions: res.data.data

          })
        } else {
          res.data.map((item, index) => {
            item.name = index + 1 + item.name
            item.yourIndex = null
          })
          this.setData({
            questions: res.data
          })
        }
        var currentIndex = 0;
        if (this.data.status == 2) {
          for (let i = 0; i < this.data.questions.length; i++) {
            if (!this.data.questions[i].answer) {
              currentIndex = i;
              break;
            }
          }
          this.setData({
            isShowContinue: true
          })
          for (let i = 0; i < this.data.questions.length; i++) {
            if (this.data.questions[i].answer) {
              let answerArr = this.data.questions[i].answer.split('|')
              console.log(answerArr)
              let yourIndex = answerArr.map(item => {
                return item == 'A' ? 0 : item == 'B' ? 1 : item == 'C' ? 2 : item == 'D' ? 3 : item == 'E' ? 4 : item == 'F' ? 5 : item == 'G' ? 6 : ''
              })
              // console.log(yourIndex)
              this.data.questions[i].yourIndex = yourIndex
              this.setData({
                questions: this.data.questions
              })
            }
          }
        }

        if (this.data.status == 3) {
          currentIndex = 0
        }
        this.setData({
          currentIndex: currentIndex
        })

      })


  },
  countdown() {
    let all_time = this.data.timing * 60;
    let t = this.data.time;
    if (t <= all_time) {
      let mimutes = Math.floor(t / 60)
      let m = mimutes < 10 ? ('0' + mimutes) : mimutes

      let seconds = Math.floor(t % 60)
      let s = seconds < 10 ? ('0' + seconds) : seconds

      this.setData({
        m,
        s,
        t: ++this.data.time
      })

      timer = setTimeout(this.countdown, 1000)
    } else {
      console.log(2)
      wx.showToast({
        title: '答题时间到,正在为你生成成绩',
        icon: 'none',
        duration: 2000,
        success: () => {
          wx.navigateTo({
            url: '/pages/realTestGrade/realTestGrade?paper_id=' + this.data.paper_id,
          })
        }
      })

      clearTimeout(timer)
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    let obj = app.globalData.test
    this.setData({
      lastTime: obj.lastTime,
      status: options.status,
      paper_id: obj.paper_id,
      type: obj.type,
      timing: obj.timing,
      totalNum: obj.totalNum,
      withoutNum: obj.withoutNum,
      subjectNum: obj.subjectNum,
      statusBarHeight: app.globalData.statusBarHeight,
      windowHeight: app.globalData.windowHeight
    })

    if (this.data.status == 1 || this.data.status == 3){
      this.setData({
        lastTime: 0
      })
    }

    console.log(this.data.lastTime)

    this.setData({
      time: this.data.lastTime * 1
    })

    this.countdown()
    this.getPaperQuestion()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearTimeout(timer)
    leftTime = this.data.time
    arr = []
    const that = this
    this.setData({
      isShowQuitTest: false
    })
    // wx.navigateBack({
    //   delta: 2
    // })
    let yourAnswers = []

    for (let i = 0; i < this.data.questions.length; i++) {
      yourAnswers[i] = {
        "subject_id": this.data.questions[i].subject_id,
        "answer": this.data.questions[i].answer ? this.data.questions[i].answer : ""
      }
    }

    console.log(yourAnswers)
    api.POST('applet/customerSubject/paperCreate', {
      paper_id: this.data.paper_id,
      status: 1,
      answer: yourAnswers,
      last_timing: this.data.time
    }, res => {
      console.log(res)
      subject_num = res.data.subject_num
    })

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})